﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KpBusiness.Model;
using KpMis.Models;
using KpBusiness.Service;
using KpMis.Utility;
using WebApp.Utility;
using System.IO;

namespace KpMis.Controllers
{ 
    public class CandidateController : Controller
    {
        private KpMisContext db = new KpMisContext();

        //
        // GET: /Candidate/

        public ViewResult CandidateMenu()
        {

            UserInformation userInformation = (UserInformation)Session[ConstantMaster.UserSessionString];
            ViewBag.UserId = userInformation.UserId;
            return View();
        }

        public ViewResult Index()
        {
            

            return View();
        }

        [HttpPost]
        public ActionResult Index(CandidateSearch candidateSearch)
        {
            
            ModelState.Remove("SearchCandidate.Fname");
            ModelState.Remove("SearchCandidate.Mobile");
            ModelState.Remove("SearchCandidate.CurrentLocation");
            ModelState.Remove("ExpFrom");
            ModelState.Remove("ExpTo");
            ModelState.Remove("SearchCandidate.Skills");
            ModelState.Remove("SearchCandidate.CurrentCtc");
            ModelState.Remove("SearchCandidate.ExpectedCtc");
            ModelState.Remove("AgeFrom");
            ModelState.Remove("AgeTo");

            CandidateService candidateService = new CandidateService();
            candidateService.SearchCandidates(candidateSearch);
            
            return View(candidateSearch);
        }

        

        //
        // GET: /Candidate/Details/5

        public ViewResult Details(int id)
        {
            Candidate candidate = new CandidateService().GetCanidate(id);
            return View(candidate);
        }

        //
        // GET: /Candidate/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Candidate/Create

        [HttpPost]
        public ActionResult Create(Candidate candidate)
        {
            if (ModelState.IsValid)
            {
                candidate = SecurityHelper.UpdateCandidateWithLogonInfo(candidate);
                new CandidateService().RegisterCandidate(candidate);
                return RedirectToAction("Index");  
            }

            return View(candidate);
        }
        
        //
        // GET: /Candidate/Edit/5
 
        public ActionResult Edit(int id)
        {
            Candidate candidate = new CandidateService().GetCanidate(id);

            //provide Default value
            if (candidate == null)
            {
                return View("Create");

            }
            else
            {
                return View(candidate);        
            }
            
        }

        //
        // POST: /Candidate/Edit/5

        [HttpPost]
        [ValidateOnlyIncomingValuesAttribute]
        public ActionResult Edit(Candidate candidate)
        {
            if (ModelState.IsValid)
            {
                if (candidate.UserInformation != null)
                {
                    Candidate candidateFromDb = new CandidateService().GetCanidate(candidate.UserInformation.UserId);
                    candidate.FileId = candidateFromDb.FileId;
                    candidate.FileExt = candidateFromDb.FileExt;
                    candidate.IsResumeUploaded = candidateFromDb.IsResumeUploaded;
                    
                    candidate.HrFileId = candidateFromDb.HrFileId;
                    candidate.HrFileExt = candidateFromDb.HrFileExt;
                    candidate.IsHrResumeUploaded = candidateFromDb.IsHrResumeUploaded;

                    candidate.OfferId = candidateFromDb.OfferId;
                    candidate.OfferFileExt = candidateFromDb.OfferFileExt;
                    candidate.IsOfferUploaded = candidateFromDb.IsOfferUploaded;

                    candidate.IsPosted = candidateFromDb.IsPosted;
                    candidate.IsLocked = candidateFromDb.IsLocked;
                    candidate.IsBlackListed = candidateFromDb.IsBlackListed;
                    candidate.CommentAboutBlackListingEvent = candidateFromDb.CommentAboutBlackListingEvent;


                }
                else
                {
                    //Create new FileId

                    candidate.FileId = Guid.NewGuid();

                    candidate.HrFileId = Guid.NewGuid();

                    candidate.OfferId = Guid.NewGuid();
                    
                }

                candidate.UserInformation = SecurityHelper.GetLiveUser();
                candidate.LastUpdatedDate = DateTime.Now;
                candidate.LastUpdatedUser = SecurityHelper.GetLiveUser().UserName;
                
                new CandidateService().UpdateCandidate(candidate);

                if (SecurityHelper.IsCurrentUserAdminOrManager() )
                {
                    return RedirectToAction("Index");    
                }
                return RedirectToAction("CandidateMenu");
            }
            return View(candidate);
        }

      
        public ActionResult UploadCv()
        {
            UserInformation userInformation = SecurityHelper.GetLiveUser();
            Candidate candidate = new CandidateService().GetCanidate(userInformation.UserId);
            return View(candidate);
        }



        public ActionResult HrResumeUpload(int id)
        {
            Candidate candidate = new CandidateService().GetCanidate(id);
            return View(candidate);
        }

        public ActionResult OfferLetterUpload(int id)
        {
            Candidate candidate = new CandidateService().GetCanidate(id);
            return View(candidate);
        }


        [HttpPost]
        [ValidateOnlyIncomingValuesAttribute]
        public ActionResult OfferLetterUpload(Candidate candidate, HttpPostedFileBase file)
        {

            if (ModelState.IsValid)
            {


                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {

                    if (file.ContentType.Contains("msword") || file.ContentType.Contains("application/pdf") || file.ContentType.Contains("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                    {
                        try
                        {
                            Candidate candidateWithResume = new CandidateService().GetCanidate(candidate.UserInformation.UserId);
                            // extract only the fielname
                            var fileName = Path.GetFileName(file.FileName);

                            // store the file inside ~/App_Data/uploads folder
                            var path = Path.Combine(Server.MapPath("~/Offers/"), candidate.OfferId.ToString() + "." + fileName.Split('.')[1]);
                            file.SaveAs(path);
                            candidateWithResume.OfferFileExt = fileName.Split('.')[1];
                            candidateWithResume.IsOfferUploaded = true;
                            new CandidateService().UpdateCandidate(candidateWithResume);
                        }
                        catch
                        {

                            if (SecurityHelper.IsCurrentUserAdminOrManager())
                            {
                                return RedirectToAction("Index");
                            }
                            return RedirectToAction("CandidateMenu");
                        }


                    }
                    else
                    {
                        ViewBag.Msg = "Please provide only word/pdf file format";
                        return View(candidate);

                    }

                }

                return RedirectToAction("Index");
            }

            return View(candidate);
        }

        [HttpPost]
        [ValidateOnlyIncomingValuesAttribute]
        public ActionResult HrResumeUpload(Candidate candidate, HttpPostedFileBase file)
        {

            if (ModelState.IsValid)
            {


                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {

                    if (file.ContentType.Contains("msword") || file.ContentType.Contains("application/pdf") || file.ContentType.Contains("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                    {
                        try
                        {
                            Candidate candidateWithResume = new CandidateService().GetCanidate(candidate.UserInformation.UserId);
                            // extract only the fielname
                            var fileName = Path.GetFileName(file.FileName);

                            // store the file inside ~/App_Data/uploads folder
                            var path = Path.Combine(Server.MapPath("~/HrResumes/"), candidate.HrFileId .ToString() + "." + fileName.Split('.')[1]);
                            file.SaveAs(path);
                            candidateWithResume.HrFileExt = fileName.Split('.')[1];
                            candidateWithResume.IsHrResumeUploaded = true;
                            new CandidateService().UpdateCandidate(candidateWithResume);
                        }
                        catch
                        {

                            if (SecurityHelper.IsCurrentUserAdminOrManager())
                            {
                                return RedirectToAction("Index");
                            }
                            return RedirectToAction("CandidateMenu");
                        }


                    }
                    else
                    {
                        ViewBag.Msg = "Please provide only word/pdf file format";
                        return View(candidate);

                    }

                }

                return RedirectToAction("Index");
            }

            return View(candidate);
        }


        public ActionResult UploadCandidateResume(int id)
        {
            UserInformation userInformation = SecurityHelper.GetLiveUser();
            Candidate candidate = new CandidateService().GetCanidate(userInformation.UserId);
            return View("UploadCv", candidate);
        }
        
        [HttpPost]
        [ValidateOnlyIncomingValuesAttribute]
        public ActionResult UploadCv(Candidate candidate, HttpPostedFileBase file)
        {

            if (ModelState.IsValid)
            {


                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {

                    if (file.ContentType.Contains("msword") || file.ContentType.Contains("application/pdf") || file.ContentType.Contains("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                    {
                        try
                        {
                            Candidate candidateWithResume = new CandidateService().GetCanidate(candidate.UserInformation.UserId);
                            // extract only the fielname
                            var fileName = Path.GetFileName(file.FileName);

                            // store the file inside ~/App_Data/uploads folder
                            var path = Path.Combine(Server.MapPath("~/Resumes/"), candidate.FileId.ToString() + "." + fileName.Split('.')[1]);
                            file.SaveAs(path);
                            candidateWithResume.FileExt = fileName.Split('.')[1];
                            candidateWithResume.IsResumeUploaded = true;
                            new CandidateService().UpdateCandidate(candidateWithResume);
                        }
                        catch
                        {

                            if (SecurityHelper.IsCurrentUserAdminOrManager())
                            {
                                return RedirectToAction("Index");
                            }
                            return RedirectToAction("CandidateMenu");
                        }


                    }
                    else
                    {
                        ViewBag.Msg = "Please provide only word/pdf file format";
                        return View(candidate);

                    }

                }

                return RedirectToAction("Index");
            }

            return View(candidate);
        }

        //
        // GET: /Candidate/Delete/5
 
        public ActionResult Delete(int id)
        {
            Candidate candidate = db.Candidates.Find(id);
            return View(candidate);
        }

        //
        // POST: /Candidate/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Candidate candidate = db.Candidates.Find(id);
            db.Candidates.Remove(candidate);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}